/*
 * Copyright (c) 2019 Author: Fancyears Milos Malvis @1243093366@qq.com
 * ALL COPYRIGHT REVERSED.
 */

package com.fancyears.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.fancyears.dao.i.user.UserDao;
import com.fancyears.dao.i.user.UserDetailDao;
import com.fancyears.dto.UserLoginDTO;
import com.fancyears.global.GlobalSetting;
import com.fancyears.model.user.User;
import com.fancyears.model.user.UserDetail;
import com.fancyears.redis.client.RedisClientDao;
import com.fancyears.redis.bean.UserSidBean;
import com.fancyears.service.i.user.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @Author: Fancyears Milos Malvis
 * @Date: Created in  2019/5/8 13:58
 * @Modified By:
 */
@Service("userService")
@Transactional(rollbackFor = {Exception.class}, propagation = Propagation.REQUIRED)
@Slf4j
public class UserServiceImpl implements UserService {
    /**
     * 用户dao
     */
    @Autowired
    private UserDao userDao;
    /**
     * 用户详情dao
     */
    @Autowired
    private UserDetailDao userDetailDao;
    /**
     * redis缓存
     */
    @Autowired
    private RedisClientDao redisClientDao;

    @Autowired
    RedisSerializer redisSerializer;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    JedisConnectionFactory jedisConnectionFactory;

    @Override
    public User getUser(Long id) {
        return userDao.selectByPrimaryKey(id);
    }

    @Override
    public boolean register(User user) {
        if (user != null) {
            return userDao.insert(user) > 0 ? true : false;
        }
        return false;
    }

    @Override
    public boolean insertWithDetail(User user, UserDetail userDetail) {
        boolean userInserted = userDao.insert(user) > 0 ? true : false;
        userDetail.setUserId(user.getId());
        boolean userDetailInserted = userDetailDao.insert(userDetail) > 0 ? true : false;
        return userInserted && userDetailInserted;
    }

    @Override
    public boolean login(Cookie[] cookies) {
        String sid = null;
        for (Cookie cookie : cookies) {
            if (GlobalSetting.SID.equals(cookie.getName())) {
                sid = cookie.getValue();
                break;
            }
        }
        if (StringUtils.isNotEmpty(sid)) {
            return redisClientDao.getValue(sid) != null ? true : false;
        }
        return false;
    }

    @Override
    public User login(User u) {
        if (StringUtils.isNotEmpty(u.getUsername()) && StringUtils.isNotEmpty(u.getPassword())) {
            User user = userDao.selectByNameAndPsw(u);
            if (user != null) {
                log.info(user.toString());
                return user;
            }
        }
        return null;
    }

    @Override
    public boolean doLogin(UserLoginDTO user, HttpServletRequest request, HttpServletResponse response) {

        User u = new User();
        u.setUsername(user.getUsername());
        u.setPassword(user.getPassword());

        Cookie[] cookies = request.getCookies();

        if (cookies != null && login(cookies)) {
            return true;
        } else {
            log.info("cookie快速登录终止");
        }

        if ((u = login(u)) != null) {
            String id = request.getSession().getId();
            Cookie sid = new Cookie(GlobalSetting.SID, id);
            sid.setPath("/");
            sid.setMaxAge(GlobalSetting.ONE_YEAR);
            sid.setHttpOnly(true);//防止被js脚本获取
            response.addCookie(sid);
            UserSidBean bean = new UserSidBean();
            bean.setUserid(u.getId());
            redisClientDao.setObject(id, bean);
            return true;
        }
        return false;
    }

    @Override
    public JSONObject doLogin2(UserLoginDTO user, HttpServletRequest request, HttpServletResponse response) throws IOException {
        User u = new User();
        u.setUsername(user.getUsername());
        u.setPassword(user.getPassword());
        u = login(u);
        JSONObject result = new JSONObject();
        boolean ok = false;
        if (u != null) {
            HttpSession session = request.getSession();
            //会直接存放在redis中
            session.setAttribute(GlobalSetting.USERNAME, u.getUsername());
            result.put(GlobalSetting.STATUS, GlobalSetting.STATUS_ENUM.OK);
            result.put(GlobalSetting.MESSAGE, "登陆成功");
            result.put(GlobalSetting.USERNAME, u.getUsername());
            ok = true;
        } else {
            result.put(GlobalSetting.STATUS, GlobalSetting.STATUS_ENUM.USERNAME_OR_PASSWORD_ERROR);
            result.put(GlobalSetting.MESSAGE, "用户名或密码错误");
            ok = false;
        }
        return result;
    }

    @Override
    public JSONObject doSignout(HttpSession session) {
        System.out.println(session.getId());
        session.removeAttribute(GlobalSetting.USERNAME);
        JSONObject result = new JSONObject();
        result.put(GlobalSetting.STATUS, GlobalSetting.STATUS_ENUM.OK);
        result.put(GlobalSetting.MESSAGE, "退出成功");
        return result;
    }

    @Override
    public JSONObject insert(int id,int type) {
        User user = new User();
        user.setUsername("xxx");
        user.setPassword("xxx");
        user.setId((long) id);
        userDao.insert(user);
        userDao.insert(user);
        if(type==2){
            throw new RuntimeException("手动回滚");
        }
        return null;
    }
}
